package com.ptu.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.ptu.server.OrderServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PayUtil {
    @Autowired
    private OrderServer orderServer;
    //appid
    private final String APP_ID = "2021000148697928";
    //应用私钥(工具)
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCAjDLPdDjGlN222jNF2Mp+4kkb5pDeEZ3e9l1712sywxD8fUcWNDSYRF93PURYdbUz/c1p+22+qNsWIPI+8vJ65UdpysAuU8quHubtfZZHCcYwiHxBqx9bsrzh4RjXLKoK9y6UKWqJrs2UzrCvZMiG7aZWKYVRJbv0vveZB0Y4QLpv9KZl/BdVfCu3fWUTY+lRadAU5v+R2QZoRd5rFH/YQidWUpiT+9TG/vAF39Mvq08jBAVsDLVD/VTiybdNMP2jfmx+x0qrVWQTZEjAxUsVVtM0qXhjKWKQo6QZVSAulkBUP8B/aTQX3oUjUodCj/OpJlmX2FaX3BxbbeiqpFF7AgMBAAECggEAc+XzqbdPuTte6w2wTLk5WU0MPWuUEaQwgmX9wzpmHE5jckJBZXOMN/ztVcSXamo2Bbo/Cd73A3+aiEkMIFVK6iLuUCPNQfeqNXMHIfipFUNqvTdRUKPIkhSE1+LrUpWiemCCTnNI6vn/wLrZ8kkbwwthfS3SVWeAHxpOglpcpTnuVTRYyHcXBq4cYMw5jIny7NLxHGDcjlVks2aT+Zw4NbMUrZ38A5Q03MfztIVQ4BHPTy677/OU+Iy5Y0iu/Ok6V8vaW8IdNtLzsJQPpmiCBzEmKtyZGUDH5aSus7tmrR8+bHJhuwuH2PoUIPy3PP+S6eqGipP1YfLj6LeuGSF9gQKBgQDHHAMG7CTN0IQ3iSPebBeR4vX41ZE42NkpDGYoc6tL5Gp64EirEa/WlofjrrZZO2ULBx2GYFl+dIbRpoZM9qW+vIslspK7OiGw1oCB6WBmX0mE0/mPR0l8IrXD5XDygXieYKXVG2zEBMW71Yz8Cr9F0B1Mw01T1K+Dq7U95oKVHwKBgQClRuZm2uPWHFeIiANQ5GxwbT+my6GBMqXxbHY+HFubt3wgORg8QAaREygFWrpDYDHRuePQXTkM42t7eLOimhh9N3lDb/SJ7Vqc1QOpwDSt4UtKPFnvq0FtyMDv+KXiOAIP+0rVOB5A6tA4cheDnrnxQV+hFZbdX4ZpA1c+EX68JQKBgAwZCZ4MDxhqSP5O2N0U2EHG9ocOAurfUiKKXFKs5IWR9V5N7lxmkLaLIuqUnQPC9hq7bfHSPN3QGrj2U0at3dg/AH1j4kJ5/74M6nX6Rh8yPvdRIeKwxChEu6KReFFjyH5nBOxz5CHs4E7PZOeTh5eoU39shnBHhfqMHlEKhnilAoGBAJpyrf5yELVWGOqKh+bA/yD0xqWc5xjv9qisPbb/ExBqH8GQ+TfccQaDS0Ptq+AodYXSW7SsWRLVNuzUN7H8pGPnQhel+HQn7SRf3yNzbQcMYSpHSZgxhlwMXVgjGQlUY4EByMWFwqfRhrEo1RZ3brWn7LCAl1HZ4aYirBVhjfhNAoGAOsIeA8kSWDdNdAXv5s+A22WYEPFWM9GAGtkve3cF9FI/h8UkTuCnz0cjSQJhlJ7EPTtneSEymB908AJY/Wfx1HXjBeNGINtR9RRD3On7cBJszlqXss8rzKd3jzmHb3ckHZFK/nCLjtUbt9o+QfF8y7dmVN26cUlvQR4IeF6u15M=";
    // 商户私钥编码
    private final String CHARSET = "UTF-8";
    // 支付宝公钥(网站)
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkPEDeBGmBlYxSDJ6E27s8ShnwMaT5I8sGmGDDVxHsGOfqzOrjNEnT37vZtoJ5YiMrYKzdERtEGWo5FwnnGG2Op3kYAeKlzmdYgvtcN3KjHURhj6HHib+4WHabvfcUgnMGNBS/dQblUEgZugmEQ96LyQ0+NVH9tImuoz6Zo7CnDytCg704I/y5s9SivkRe/WYgMChtuW2dFFzUVPV4y+SpQ7uJNil2evdohN/PlSrLL+10OXtkNDpX57eZDYleGUucj5WGCH8u1K86pdxFVcurbHB0MesiWQqpIDoBC1FBOuGV/ljdBnzGnOrkihCUjkR/qqexLU+9KaJm4dXZTZnmQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do"; 
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址（内网穿透）（支付成功后调用的接口方法）
    private final String NOTIFY_URL = "http://kcc3b6fd.natappfree.cc/api/alipay/toSuccess";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址（项目端口）（跳转到订单列表页）
    private final String RETURN_URL = "http://localhost:5173/orders";
    private AlipayClient alipayClient = null;
    //支付宝官方提供的接口（传入订单编号，支付金额，对象）
    public String sendRequestToAlipay(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("返回的结果是："+result );
        return result;
    }

    //    通过订单编号查询支付状态
    public String query(String id){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        String body=null;
        try {
            response = alipayClient.execute(request);
            body = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return body;
    }
}
